package com.example.newsapp.activity;

import static com.example.newsapp.constant.NetConstant.BASE_URL;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.newsapp.R;
import com.example.newsapp.model.request.RegisterRequest;
import com.example.newsapp.model.Result;
import com.example.newsapp.utils.HttpUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

public class RegisterActivity extends AppCompatActivity {
    private EditText etUsername, etPassword, etConfirmPassword;
    private Button btnRegister;
    private TextView tvGoLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initViews();
        setupListeners();
    }

    private void initViews() {
        findViewById(R.id.btnBack).setOnClickListener(v -> finish());
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);
        btnRegister = findViewById(R.id.btnRegister);
        tvGoLogin = findViewById(R.id.tvGoLogin);
    }

    private void setupListeners() {
        btnRegister.setOnClickListener(v -> attemptRegister());
        tvGoLogin.setOnClickListener(v -> startActivity(new Intent(this, LoginActivity.class)));
    }

    private void attemptRegister() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!password.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        btnRegister.setEnabled(false);
        performRegister(username, password);
    }

    private void performRegister(String username, String password) {
        RegisterRequest registerRequest = new RegisterRequest(username, password);

        String requestUrl = BASE_URL + "/users/register";
        Type resultType = new TypeToken<Result<String>>() {
        }.getType();
        HttpUtil.request(RegisterActivity.this,requestUrl, "POST", registerRequest, resultType, new HttpUtil.Callback<Result<String>>() {
            @Override

            public void onSuccess(Result<String> result) {
                handleRegisterResult(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("网络异常，注册失败");
            }
        });
    }

    private void handleRegisterResult(Result<String> response) {

        if (response == null) {
            showToast("服务器响应异常");
            btnRegister.setEnabled(true);
            return;
        }

        if (response.getCode() == 1 && response.getData() != null) {
            String data = response.getData();
            Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
            finish();
        } else {
            String errorMsg = response.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) {
                errorMsg = "未知错误";
            }
            showToast(errorMsg);
        }
        btnRegister.setEnabled(true);

    }

    private void showToast(String msg) {
        Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}
